import React, { useEffect, useState } from "react";
import { Button, Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import { getbooklist } from "../../axios/index";
import type { PopconfirmProps } from "antd";
import { message, Popconfirm } from "antd";
import { Modal, Form, Input } from "antd";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import {
  SearchOutlined,
  FormOutlined,
  ArrowUpOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import axios from "../../axios/axios";
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
  categories: string[];
}
function List() {
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState("<p>hello</p>");

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setTimeout(() => {
      setHtml("");
    }, 1500);
  }, []);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "Tags",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag: any) => {
            let color = tag.length > 5 ? "geekblue" : "green";
            if (tag === "loser") {
              color = "volcano";
            }
            return (
              <Tag color={color} key={tag.name}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "categories",
      key: "categories",
      dataIndex: "categories",
      render: (_, { categories }) => (
        <>
          {categories.map((categories: any) => {
            return (
              <Tag color={"blue"} key={categories.name}>
                {categories.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "浏览量",
      dataIndex: "viewCount",
      key: "viewCount",
    },
    {
      title: "发布时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "修改时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },

    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            shape="circle"
            onClick={showModal}
            icon={<SearchOutlined />}
          />
          <Button
            type="primary"
            shape="circle"
            onClick={() => {
              setisTJModalOpen(true);
              setTitle("编辑");
              setEdid(record.id);
            }}
            icon={<FormOutlined />}
          />
          <Button type="primary" shape="circle" icon={<ArrowUpOutlined />} />
          <Popconfirm
            title="删除"
            description="你真的要删除吗"
            onConfirm={() => henddelete(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [data, setData] = useState([]);
  const [keyword, setKeyword] = useState("");
  const [title, setTitle] = useState("");
  const [edid, setEdid] = useState("");
  const getbooklist = () => {
    axios({
      url: "http://blogapi.shbwyz.com/article/list",
      method: "get",
      params: {
        keyword,
      },
    }).then((res) => {
      console.log(res);
      setData(res.data.rows);
    });
  };
  useEffect(() => {
    getbooklist();
  }, [keyword]);

  const onFinish = (values: any) => {
    console.log("Success:", values);
    const { keyword } = values;
    setKeyword(keyword);
    getbooklist();
  };

  const cancel: PopconfirmProps["onCancel"] = (e) => {
    console.log(e);
    message.error("取消删除");
  };
  const henddelete = (id: number) => {
    axios({
      url: `http://blogapi.shbwyz.com/article/${id}`,
      method: "delete",
    }).then((res) => {
      console.log(res);
      getbooklist();
      message.success("删除成功");
    });
  };

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    setisTJModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setisTJModalOpen(false);
  };

  const [isTJModalOpen, setisTJModalOpen] = useState(false);

  const showTJModal = () => {
    setisTJModalOpen(true);
  };

  const onTJFinish = (values: any) => {
    if (title === "添加") {
      axios({
        url: "http://blogapi.shbwyz.com/article",
        method: "post",
        data: {
          title: values.title,
          content: html,
          authorId: "47529555",
        },
      }).then((res) => {
        console.log(res);
        getbooklist();
        message.success("添加成功");
        setisTJModalOpen(false);
      });
    } else {
      axios({
        url: `http://blogapi.shbwyz.com/article/${edid}`,
        method: "put",
        data: {
          title: values.title,
          content: html,
        },
      }).then((res) => {
        console.log(res);
        getbooklist();
        message.success("修改成功");
        setisTJModalOpen(false);
      });
    }
  };
  return (
    <div>
      <div>
        <Form
          layout="inline"
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item label="标题" name="keyword">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Form.Item label={null}>
            <Button
              type="primary"
              onClick={() => {
                showTJModal();
                setTitle("添加");
              }}
            >
              添加
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table<DataType> columns={columns} dataSource={data} />
      <div>
        <Modal
          title="Basic Modal"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          {data.map((item) => {
            return <p>{item.title}</p>;
          })}
        </Modal>
      </div>
      <div>
        <Modal
          title={title}
          open={isTJModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onTJFinish}
            autoComplete="off"
          >
            <Form.Item label="标题" name="title">
              <Input />
            </Form.Item>
            <Form.Item label="内容" name="content">
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => setHtml(editor.getHtml())}
                mode="default"
                style={{ height: "500px", overflowY: "hidden" }}
              />
            </Form.Item>

            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
}

export default List;
